﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Transactions;

namespace WebApplication1.MyFilters
{
    /// <summary>
    /// 事务过滤器
    /// </summary>
    public class TransactionScopeFilter: IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            bool hasNotTransactionAttribute = false;
            if(context.ActionDescriptor is ControllerActionDescriptor)
            {
                var actionDesc = (ControllerActionDescriptor)context.ActionDescriptor;
                hasNotTransactionAttribute = actionDesc.MethodInfo.IsDefined(typeof(NotTransactionalAttribute), true);
            }
            if (hasNotTransactionAttribute)
            {
                await next();
                return;
            }
            // 因为 OnActionExecutionAsync 是异步的，所以需要使用 TransactionScopeAsyncFlowOption.Enabled
            using var txScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
            var result = await next();
            if (result.Exception != null)
            {
                // 事务回滚
                txScope.Dispose();
                return;
            }
            else
            {
                // 事务提交
                txScope.Complete();
            }
        }
    }
}
